<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="queryData">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="showForm()" type="primary" size="small">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>
        <a-button @click="confirmBatchDelete" type="danger" size="small">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table
      size="small"
      :dataSource="tableData"
      :columns="columns"
      rowKey="id"
      bordered
      :loading="tableLoading"
      :pagination="false"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
      <template #bodyCell="{ text, record, column }">
        <div v-if="column.dataIndex === 'jsonInput'" class="smart-table-operate">
          <a-button @click="inputApi(record)" type="link">详情</a-button>
        </div>
        <div v-if="column.dataIndex === 'action'" class="smart-table-operate">
          <a-button @click="showForm(record)" type="link">编辑</a-button>
          <a-button @click="onDelete(record)" danger type="link">删除</a-button>
        </div>
      </template>
    </a-table>
    <!---------- 表格 end ----------->
    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNum"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <!-- <ApiJsonForm ref="formRef" :isEditMode="isEditMode" @reloadList="queryData" /> -->

    <br />
    <br />
    <br />
    <!---------- 详情表格 begin ----------->
    <div v-if="showDetail">
      <a-button type="primary" size="small" style="margin-bottom: 12px" @click="inuta"
        ><template #icon>
          <PlusOutlined />
        </template>
        新增
      </a-button>
      <a-table
        size="small"
        :dataSource="detailData"
        :columns="detailColumns"
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="QueryForm.pageSize"
        v-model:current="QueryForm.pageNum"
        v-model:pageSize="QueryForm.pageSize"
        rowKey="id"
        bordered
        :pagination="false"
      >
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate">
              <a-button @click="showForm(record)" type="link">编辑</a-button>
              <a-button @click="apiDelete(record)" danger type="link">删除</a-button>
            </div>
          </template>
        </template>
      </a-table>
      <div class="smart-query-table-page">
        <a-pagination
          showSizeChanger
          showQuickJumper
          show-less-items
          :pageSizeOptions="PAGE_SIZE_OPTIONS"
          :defaultPageSize="QueryForm.pageSize"
          v-model:current="QueryForm.pageNum"
          v-model:pageSize="QueryForm.pageSize"
          :total="total"
          @change="QueryData"
          @showSizeChange="QueryData"
          :show-total="(total) => `共${total}条`"
        />
      </div>
      <a-button @click="hideDetail" type="default">隐藏详情</a-button>
    </div>
    <!---------- 详情表格 end ----------->

    <!-- ————————————————————————————————————详情添加———————————————————————————————— -->
    <a-modal v-model:open="deo" title="添加" @ok="handleOk()">
      <a-form :model="addfm" :rules="rules" :label-col="{ span: 5 }">
        <a-form-item label="inputCode">
          <a-input style="width: 60%" v-model:value="addfm.inputCode" placeholder="" />
        </a-form-item>
        <a-form-item label="inputKey">
          <a-input style="width: 60%" v-model:value="addfm.inputKey" placeholder="" />
        </a-form-item>
        <a-form-item label="inputValue">
          <a-input style="width: 60%" v-model:value="addfm.inputValue" placeholder="" />
        </a-form-item>
        <a-form-item label="inputNote">
          <a-input style="width: 60%" v-model:value="addfm.inputNote" placeholder="" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup>
import { message, Modal } from "ant-design-vue";
import { onMounted, reactive, ref } from "vue";
import { apiJsonApi } from "/@/api/business/api-json/api-json-api";
import { SmartLoading } from "/@/components/framework/smart-loading";
import TableOperator from "/@/components/support/table-operator/index.vue";
import { PAGE_SIZE_OPTIONS } from "/@/constants/common-const";
import { smartSentry } from "/@/lib/smart-sentry";

//----------------------------表格列----------------------------;
const columns = ref([
  { title: "编码", dataIndex: "jsonCode", ellipsis: true },
  { title: "协议类型", dataIndex: "jsonHost", ellipsis: true },
  { title: "ip", dataIndex: "jsonIp", ellipsis: true },
  { title: "端口", dataIndex: "jsonPort", ellipsis: true },
  { title: "请求类型", dataIndex: "jsonType", ellipsis: true },
  { title: "路径", dataIndex: "jsonUrl", ellipsis: true },
  { title: "输入参数", dataIndex: "jsonInput" },
  { title: "注释", dataIndex: "jsonNote", ellipsis: true },
  { title: "输出", dataIndex: "jsonOutput", ellipsis: true },
  { title: "输出url", dataIndex: "jsonOuturl", ellipsis: true },
  { title: "操作", dataIndex: "action", fixed: "right", width: 90 },
]);
const detailColumns = ref([
  {
    title: "inputCode",
    dataIndex: "inputCode",
    ellipsis: true,
  },
  {
    title: "inputKey",
    dataIndex: "inputKey",
    ellipsis: true,
  },
  {
    title: "inputValue",
    dataIndex: "inputValue",
    ellipsis: true,
  },
  {
    title: "inputNote",
    dataIndex: "inputNote",
    ellipsis: true,
  },
  {
    title: "jsonCode",
    dataIndex: "jsonCode",
    ellipsis: true,
  },
  { title: "操作", dataIndex: "action", fixed: "right", width: 90 },
]);

const queryFormState = { pageNum: 1, pageSize: 10 };
const queryForm = reactive({ ...queryFormState });

const QueryFormState = { pageNum: 1, pageSize: 10 };
const QueryForm = reactive({ ...QueryFormState });
const tableLoading = ref(false);
const tableData = ref([]);
const total = ref(0);
const inputData = ref([]);
const inputtotal = ref(0);
const showDetail = ref(false); // 控制详情表格的显示
const detailData = ref([]); // 存储详情数据
const deo = ref(false);
const addfm = ref({
  inputCode: "",
  inputKey: "",
  inputValue: "",
  inputNote: "",
  jsonCode: "",
});
// 重置查询条件
function resetQuery() {
  let pageSize = queryForm.pageSize;
  Object.assign(queryForm, queryFormState);
  queryForm.pageSize = pageSize;
  queryData();
}

// 查询数据
async function queryData() {
  tableLoading.value = true;
  try {
    let queryResult = await apiJsonApi.queryPage(queryForm);
    tableData.value = queryResult.data.list;
    total.value = queryResult.data.total;
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    tableLoading.value = false;
  }
}

async function QueryData() {
  tableLoading.value = true;
  try {
    let queryResult = await apiJsonApi.QueryPage(QueryForm);
    inputData.value = queryResult.data.list;
    inputtotal.value = queryResult.data.total;
  } catch (error) {
    console.log(error);
  } finally {
    tableLoading.value = false;
  }
}

onMounted(() => {
  queryData();
  QueryData();
});
async function inputApi(record) {
  // 获取所有详情数据
  try {
    let queryResult = await apiJsonApi.QueryPage(QueryForm);
    const allDetails = queryResult.data.list;

    // 根据当前记录的 jsonCode 进行过滤
    detailData.value = allDetails.filter((detail) => detail.jsonCode === record.jsonCode);

    addfm.value.jsonCode = record.jsonCode;
    // 显示详情表格
    showDetail.value = true;
  } catch (error) {
    console.error("获取详情数据失败:", error);
  }
}
function hideDetail() {
  showDetail.value = false;
}
function inuta() {
  deo.value = true;
}
const handleOk = async (e) => {
  console.log(e);
  deo.value = false;
  try {
    await apiJsonApi.Inputadd(addfm.value);
    QueryData();
  } catch (error) {
    console.log(error);
  }
};
// ---------------------------- 添加/修改 ----------------------------
const formRef = ref();
const isEditMode = ref(false);

function showForm(data) {
  isEditMode.value = !!data;
  formRef.value.show(data);
}

// ---------------------------- 单个删除 ----------------------------
function onDelete(data) {
  Modal.confirm({
    title: "提示",
    content: "确定要删除选吗?",
    okText: "删除",
    okType: "danger",
    onOk() {
      requestDelete(data);
    },
    cancelText: "取消",
  });
}

async function requestDelete(data) {
  SmartLoading.show();
  try {
    await apiJsonApi.delete(data.jsonCode);
    message.success("删除成功");
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}
function apiDelete(data) {
  Modal.confirm({
    title: "提示",
    content: "确定要删除选吗?",
    okText: "删除",
    okType: "danger",
    onOk() {
      requestapiDelete(data);
    },
    cancelText: "取消",
  });
}
async function requestapiDelete(data) {
  SmartLoading.show();
  try {
    await apiJsonApi.apidelete(data.inputCode);
    message.success("删除成功");
    QueryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}
// ---------------------------- 批量删除 ----------------------------
const selectedRowKeys = ref([]);
const onSelectChange = (selectedRowKeys) => {
  console.log("selectedRowKeys changed: ", selectedRowKeys);
  selectedRowKeys.value = selectedRowKeys;
};

function confirmBatchDelete() {
  Modal.confirm({
    title: "提示",
    content: "确定要批量删除这些数据吗?",
    okText: "删除",
    okType: "danger",
    onOk() {
      requestBatchDelete();
    },
    cancelText: "取消",
  });
}
async function requestBatchDelete() {
  try {
    SmartLoading.show();
    await apiJsonApi.batchDelete(selectedRowKeys.value);
    message.success("删除成功");
    queryData();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}
</script>
